package handlers

import (
	"chatgpt/models"
	"chatgpt/pkg/service"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ChatHandler struct {
	chatService service.ChatService
}

func NewChatHandler(chatService service.ChatService) *ChatHandler {
	return &ChatHandler{chatService: chatService}
}

func (h *ChatHandler) RegisterRoutes() *gin.Engine {
	router := gin.Default()

	router.Use(corsMiddleware())
	router.NoRoute(gin.WrapH(http.FileServer(http.Dir("public"))))

	api := router.Group("/api")
	{
		api.POST("/interact", h.handleInteraction)
		api.GET("/history", h.fetchChatHistory)
		api.GET("/clearhistory", h.clearChatHistory)
	}

	return router
}

func (h *ChatHandler) clearChatHistory(c *gin.Context) {

	id := c.Query("id")

	if id == "" {
		c.JSON(http.StatusBadRequest, "ID is required")
		return
	}

	err := h.chatService.ClearChatHistory(id)
	if err != nil {
		respondWithError(c, http.StatusInternalServerError, err.Error())
	}
	c.JSON(http.StatusOK, "история чата очищена")
}
func (h *ChatHandler) fetchChatHistory(c *gin.Context) {
	id := c.Query("id_profile")

	res, err := h.chatService.FetchAllMessages(id)
	if err != nil {
		respondWithError(c, http.StatusInternalServerError, err.Error())
		return
	}
	c.JSON(http.StatusOK, res)
}

func (h *ChatHandler) handleInteraction(c *gin.Context) {
	var chatMessage models.ChatMessage
	if err := c.BindJSON(&chatMessage); err != nil {
		respondWithError(c, http.StatusBadRequest, err.Error())
		return
	}

	err := h.chatService.GenerateResponse(chatMessage)
	if err != nil {
		respondWithError(c, http.StatusInternalServerError, err.Error())
		return
	}

	c.JSON(http.StatusCreated, "запрос отправлен")
}

func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusOK)
			return
		}

		c.Next()
	}
}
